﻿;(function ($, window) {
    $.UniqueBox = function (options) {
        var _uniqueBox = {
            options: {
                targetDiv:"",
                containerClass:"ui-uniquebox",
                maxSize:4,
                uniqueBoxContainerId : 'uniqueBox' + options.targetDiv,
                configSubmitBtn : true,
                submitBtnTip:"提交",
                setValueAbleWhenFull:true,
                onAdd:function (key,box) {},
                onRemove:function (key,box) {},
                onSubmit:function (valCsvParam) {},
                getKeepPersistedValueHtmlTagSelector:function (key) {},
                onAllBoxIsFilled:function () {},
                persistBoxValCookieKey:'uniqueBoxVals'
            },

            init:function () {
                var options = _uniqueBox.options;

                //初始化结构
                var structureHTML = '<div id="' + options.uniqueBoxContainerId + '" class="'+options.containerClass+'"><ul>';
                var i = 1;
                for(;i <= options.maxSize ; i ++) {
                    structureHTML +='<li uniqueVal=""><dt>'+i+'</dt><dd>您还可以继续添加</dd></li>';
                }

                var submitBtnId = options.uniqueBoxContainerId + "SubmitBt";
                var submitBtnDiv = "";
                if (options.configSubmitBtn) {
                    submitBtnDiv = '<div class="ui-uniquebox-getvalbtn"><a id="' + submitBtnId + '">'+options.submitBtnTip+'</a></div>';
                }
                structureHTML += '</ul>'+submitBtnDiv+'</div>';

                $("#" +options.targetDiv).html(structureHTML);

                //取得cookie中的信息对box中的信息进行回显。
                // 说明：所有cookie中需要保存的信息，都保存到一个html标签中。存储时，以【key:html标签】,【key:html标签】...的方式进行保存。
                // 取得cookie中的信息，如果当前页面中已经存在某个key，那么就什么也不做，否则就把key对应的html标签追加至hiddenDiv中，最后把hiddenDiv追加至当前页面的body中。
                var hiddenDiv = $('<div id="'+options.uniqueBoxContainerId+ 'KeepCookieValHiddenDiv" style="display:none"></div>');
                var cookieVal = $.cookie(options.persistBoxValCookieKey);

                if (cookieVal) {
                    var keyAndValues = cookieVal.split(",");
                    //alert(keyAndValues);
                    $.each(keyAndValues, function (i, item) {
                        var keyAndValue = item.split(":");

                        var selector = options.getKeepPersistedValueHtmlTagSelector.call(this, keyAndValue[0]);
                        //如果cookie中的用来保存信息的html不在当前页面，那么就保存到一个隐藏的hiddenDiv中。
                        if (!$(selector).get(0)) {
                            $(hiddenDiv).append(keyAndValue[1]);
                        }
                    });

                    $("body").append(hiddenDiv);

                    $.each(keyAndValues, function (i, item) {
                        var keyAndValue = item.split(":");
                        _uniqueBox.add(keyAndValue[0]);
                    });
                }

                $("#" + submitBtnId).click(function() {
                    options.onSubmit.call(this, _uniqueBox.getAllValCsvParam("", true));
                });

            },
            //保存盒子中所有的信息到cookie中
            refreshCookieVal:function () {
                var options = _uniqueBox.options;
                var cookieSaveVal = "";
                $("#" + options.uniqueBoxContainerId + ">ul>li[uniqueVal]").each(function () {
                    var key = $(this).attr("uniqueVal");
                    if (key && key != '') {
                        //通过getKeepPersistedValueHtmlTagSelector()取得当前页面中保存要进行持久化的数据的htmltag的selector，从而获得其html内容
                        var selector = options.getKeepPersistedValueHtmlTagSelector.call(this, key);
                        var value = $("<p>").append($(selector).clone()).html();;
                        cookieSaveVal += key + ":" + value + ",";
                    }
                });

                if (cookieSaveVal.match(/,$/)) {
                    cookieSaveVal = cookieSaveVal.substring(0, cookieSaveVal.length - 1);
                }

                //存入cookie中。
                $.cookie(options.persistBoxValCookieKey,cookieSaveVal, {expires:7});
            },

            add:function (key) {
                var options = _uniqueBox.options;
                //如果不允许在盒子满的情况下继续添加内容，那么就返回，什么都不做。
                if (_uniqueBox.allBoxIsFilled()) {
                    options.onAllBoxIsFilled.call(this);
                }
                if (!options.setValueAbleWhenFull && _uniqueBox.allBoxIsFilled()) {
                    return;
                }
                var sameVal = $("#" + options.uniqueBoxContainerId + ">ul>li[uniqueVal=" + key + "]").get(0);
                if(!sameVal) {
                    //alert(key);
                    var toSetValItem = $("#" + options.uniqueBoxContainerId + ">ul>li[uniqueVal=]:first").get(0);
                    //如果盒子已经满了，先删除最后一个盒子中的信息，再向其中添加新的信息。
                    if (!toSetValItem) {
                        toSetValItem = $("#" + options.uniqueBoxContainerId + ">ul>li:last").get(0);
                        _uniqueBox.remove($(toSetValItem).attr("uniqueVal"));
                    }

                    $(toSetValItem).attr("uniqueVal", key);
                    options.onAdd.call(this, key, toSetValItem);

                    _uniqueBox.refreshCookieVal();
                }
            },

            remove:function (key) {
                //alert($("#" + options.uniqueBoxContainerId + ">ul>li[uniqueVal=" + key + "]").attr("uniqueVal"));
                var options = _uniqueBox.options;
                //$("#" + options.uniqueBoxContainerId + ">ul>li[uniqueVal=" + key + "]>img").attr("src",options.defaultIconPath);
                var toRemoveItem = $("#" + options.uniqueBoxContainerId + ">ul>li[uniqueVal=" + key + "]").get(0);
                if (toRemoveItem) {
                    $(toRemoveItem).attr("uniqueVal","");
                    var itemIndex = ($("#" + options.uniqueBoxContainerId + ">ul>li").index(toRemoveItem) + 1);
                    $(toRemoveItem).html('<dt>'+ itemIndex+'</dt><dd>您还可以继续添加</dd>');
                    options.onRemove.call(this, key, toRemoveItem);
                    _uniqueBox.refreshCookieVal();
                }

            },
            removeAll:function () {
                var allKeys = _uniqueBox.getAllValCsvParam("", true).split(",");
                $.each(allKeys, function (i, key) {
                    _uniqueBox.remove(key);
                });
            },
            allBoxIsFilled:function() {
                var options = _uniqueBox.options;
                if ($("#" + options.uniqueBoxContainerId + ">ul>li[uniqueVal=]:first").get(0)) {
                    return false;
                } else {
                    return true;
                }
            },
            getFilledBoxCount: function () {
                var options = _uniqueBox.options;
                return $("#" + options.uniqueBoxContainerId + ">ul>li[uniqueVal!='']").length
            },
            getAllValCsvParam:function (paramName, withNoParamName) {
                var options = _uniqueBox.options;
                if (!paramName) {
                    paramName = 'uniqueBoxVals=';
                } else {
                    paramName+="="
                }

                if (withNoParamName) {
                    paramName = "";
                }
                $("#" + options.uniqueBoxContainerId + ">ul>li[uniqueVal]").each(function () {
                    var key = $(this).attr("uniqueVal");
                    if (key && key != '') {
                        paramName += key + ",";
                    }
                });

                if (paramName.match(/,$/)) {
                    paramName = paramName.substring(0, paramName.length - 1);
                }

                return paramName;
            },

            exposeInterface: function () {
                this.add = _uniqueBox.add;
                this.remove = _uniqueBox.remove;
                this.removeAll = _uniqueBox.removeAll;
                this.onAllBoxIsFilled = _uniqueBox.onAllBoxIsFilled;
                this.getAllValCsvParam = _uniqueBox.getAllValCsvParam;
                this.getFilledBoxCount = _uniqueBox.getFilledBoxCount;
                this.exposeInterface = _uniqueBox.exposeInterface;
            }

        };

        _uniqueBox.options =  $.extend(_uniqueBox.options, options);


        _uniqueBox.init();

        _uniqueBox.exposeInterface.call(this);


        return this;
    };
})(jQuery, window);
